package com.ruoyi.factory.manpower.utils;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.factory.qylock.utils.OkHttpUtils;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SignHelper {
    protected static final Logger logger = LoggerFactory.getLogger(com.ruoyi.factory.estimate.utils.SignHelper.class);

    private static String appKey = "a67b62d6e4e84e0bb1c8669bd9b91847";
    private static String appSecret = "a5296fbf18ab89bb212aa7ad87cb389863e9a989";
    private static String url = "https://c2.yonyoucloud.com/iuap-api-auth/open-auth/selfAppAuth/getAccessToken";
    /**
     * @author: Liujiaji
     * @date: 2023/4/23 0023 14:56
     * @description: TODO 友空间免登获取token加密工具
     * @param: [params, suiteSecret]
     * @return: java.lang.String
     **/
    public static String sign(Map<String, String> params, String suiteSecret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        // use tree map to sort params by name
        Map<String, String> treeMap;
        if (params instanceof TreeMap) {
            treeMap = params;
        } else {
            treeMap = new TreeMap<>(params);
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : treeMap.entrySet()) {
            stringBuilder.append(entry.getKey()).append(entry.getValue());
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(suiteSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
        String base64String = Base64.getEncoder().encodeToString(signData);
        return URLEncoder.encode(base64String, "UTF-8");
    }

    /**
     * @author: Liujiaji
     * @date: 2023/4/23 0023 14:57
     * @description: TODO 友空间获取token
     * @param: []
     * @return: java.lang.String
     **/
    public static String getToken (){
        String sign = "";
        String result = "";
        String timecur = String.valueOf(System.currentTimeMillis());
        String s = "appKey"+appKey+"timestamp"+timecur;
        logger.info("待加密数据"+s);
        Map<String, String> map = new HashMap<>();
        map.put("appKey",appKey);
        map.put("timestamp",timecur);
        try {
            sign = sign(map, appSecret);
            logger.info("sha256加密后数据"+sign);
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appKey", appKey);
            paramMap.put("timestamp", timecur);
            paramMap.put("signature", sign);
            String paramj = JSON.toJSONString(paramMap);
            logger.info("请求友空间url "+url);
            logger.info("请求友空间获取免登token入参: "+ paramj);
            result = OkHttpUtils.okHttpGet(url, paramMap);
            System.out.println("请求友空间获取免登token返参: "+result);
        } catch (Exception e) {
            logger.error("请求友空间获取免登token异常",e.getMessage());
        }finally{
            JSONObject jsonObject = JSONObject.fromObject(result);
            String code1 = jsonObject.optString("code");
            if("00000".equals(code1)){
                //获取token成功
                String data = jsonObject.optString("data");
                JSONObject data2 = JSONObject.fromObject(data);
                String access_token = data2.optString("access_token");
                return access_token;
            }else{
                return null;
            }

        }
    }

}

